from socket import *
from matplotlib import pyplot as plt
import sys, os, struct
import math
from threading import Thread, Lock
from time import sleep
import numpy as np
from matplotlib.widgets import Button
import sklearn
import scipy.signal as signal
import sklearn


sys.path.append(os.path.join(sys.path[0], '../..'))

from csi_data import CSI_Data
from csi_config import read_setting

PORT = int(read_setting('port'))

BUF_SIZE = 2048
client = socket(AF_INET, SOCK_STREAM, 0)
client.connect(('127.0.0.1', PORT))
totalcnt = 0


def getmodl(arr):
    return [math.sqrt(item.real ** 2 + item.imag ** 2) for item in arr]


def getmod(item):
    # return math.sqrt(item.real ** 2 + item.imag ** 2)
    return np.abs(item)

def getphase(item):
    return np.angle(item)


def read_t():
    alive = True
    while alive:
        try:
            buf = client.recv(BUF_SIZE)
            # print(buf)
            if buf is None:
                client.close()
                sys.exit(-2)
            i = struct.unpack('>H', buf[:2])
            print(len(buf))
            if i[0] == len(buf) - 2:  # correct package check - 1
                global totalcnt
                totalcnt += 1

                if buf[2] == 187:  # correct package check - 2
                    dat = CSI_Data(buf[3:])
                    # print(dat)
                    # csi_update(dat)#观察幅值的差
                    # csi_process_phase(dat)#观察相位差
                    # csi_process(dat)
        except struct.error as e:
            alive=False
            print(e)
            client.close()



# csi数据更新
def csi_update(dat):
    if dat is not None:
        print(dat.correct)
        csi_t = dat.csi[0][0]
        l[0][0].set_ydata(getmodl(csi_t))
        csi_t = dat.csi[0][1]
        l[1][0].set_ydata(getmodl(csi_t))
        csi_t = [0] * 30
        for i in range(30):
            csi_t[i] = abs(getmod(dat.csi[0][0][i]) - getmod(dat.csi[0][1][i]))
        l[2][0].set_ydata(csi_t)
        plt.draw()


# csi数据处理--两个天线30个子载波m的模的差作平均
def csi_process(dat):
    if dat is not None:
        print(dat.correct,dat.Ntx,dat.Nrx)
        csi_y.reverse()
        csi_t = [0] * 30
        for i in range(10,20):
            # csi_t[i] = abs(getmod(dat.csi[0][0][i]) - getmod(dat.csi[0][1][i]))
            csi_t[i] = getmod(dat.csi[0][0][i])
        csi_sum = np.sum(csi_t)/len(csi_t)
        csi_sum = getmod(dat.csi[0][0][15])

        # csi_sum = np.var(csi_t)
        csi_y.append(csi_sum)
        csi_y.remove(csi_y[0])
        csi_y.reverse()

        # 低通滤波器
        # b, a = signal.butter(8, 0.2, 'low')
        # sf = signal.filtfilt(b, a, csi_y)
        line[0].set_ydata(csi_y)
        plt.draw()


# csi数据处理--两个天线30个子载波的相位差作平均
def csi_process_phase(dat):
    if dat is not None:
        print(dat.correct)
        csi_y.reverse()
        csi_t = [0] * 30
        for i in range(30):
            csi_t[i] = getphase(dat.csi[0][0][i]) - getphase(dat.csi[0][1][i])
        csi_sum = np.sum(csi_t)/len(csi_t)
        # csi_sum = getphase(dat.csi[0][0][0])
        csi_y.append(csi_t[9])
        csi_y.remove(csi_y[0])
        csi_y.reverse()
        line[0].set_ydata(csi_y)
        plt.draw()



plt.figure(1)
plt.ylim(-1 * 5, 5)
# plt.ylim(0, 100)

l = [None, None, None]
l[0] = plt.plot(range(1, 31), [0 for _ in range(30)], 'ro')
l[1] = plt.plot(range(1, 31), [0 for _ in range(30)], 'bx')
# plt.figure()
# plt.ylim(0,20)
l[2] = plt.plot(range(1, 31), [0 for _ in range(30)], 'g')


num = 200
csi_y = [0] * num
line = plt.plot(range(0, num), [0 for _ in range(num)], 'r') #经数据处理之后的图线

read_thread = Thread(target=read_t)

read_thread.start()
plt.show()
read_thread.join()
